//============================================================================
// Name        : IndexBuilder.h
// Author      : lucmir@dcc.ufmg.br
// Description :
//============================================================================

#ifndef __INDEX_BUILDER_H__
#define __INDEX_BUILDER_H__

#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <queue>

#include "Run.h"
#include "Lexon.h"
#include "Registry.h"
#include "Index.h"
#include "DocumentIndex.h"

#define MAX_RUN_SIZE	BUFFER_SIZE		// Max run size in number of registries


class IndexBuilder {

	/**
	 *  Inner class used during the index generation
	 */
	class IndexRegistry {
		public:
			Registry registry;
			unsigned int runId;

			bool operator<(const IndexRegistry &ir) const {
				return (this->registry > ir.registry);
			}

			IndexRegistry() : registry(Registry(0, 0, 0)) {}
	};

	Run *run;
	Lexon *lexon;
	DocumentIndex *docIdx;
	Index *index;
	std::string tmpDir;
	unsigned int runsCount;		// Number of runs created (number of files)


	public:

		IndexBuilder();
		IndexBuilder(std::string tmpDir);
		~IndexBuilder();

		/*
		 * A new run in file is created if necessary
		 * (if the maximum number of records reaches MAX_RUN_SIZE).
		 */
		void manageRuns(Lexon *lexon);

		/*
		 *	Build the Index by merging the runs in file
		 */
		bool buildIndex();

		/*
		 * Writes run to file and clean the structure in memory
		 */
		void writeRunToFile(Lexon *lexon);

		Lexon *getLexon();
		DocumentIndex *getDocIdx();
		Run *getRun();
		Index *getIndex();
};

#endif
